package com.dlc.shop.discount.multishop.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dlc.shop.bean.enums.ProdStatusEnums;
import com.dlc.shop.bean.model.Product;
import com.dlc.shop.bean.param.ProductParam;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.i18n.I18nMessage;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.common.util.PageParam;
import com.dlc.shop.discount.common.model.Discount;
import com.dlc.shop.discount.common.service.DiscountService;
import com.dlc.shop.security.multishop.util.SecurityUtils;
import com.dlc.shop.service.ProductService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;


/**
 * @author lgh on 2018/11/21.
 */
@RestController
@RequestMapping("/admin/discountProd")
@Tag(name = "商家端促销活动商品接口")
@AllArgsConstructor
public class DiscountProdController {

    private final DiscountService discountService;

    private final ProductService productService;

    @GetMapping("/info/{discountId}")
    @Operation(summary = "根据活动id获取促销活动商品信息")
    @PreAuthorize("@pms.hasPermission('admin:discountProd:info')")
    @Parameter(name = "discountId", description = "活动ID" , required = true)
    public ServerResponseEntity<IPage<Product>> info(@PathVariable("discountId") Long discountId, ProductParam product, PageParam<Product> page) {
        Discount discount = discountService.getById(discountId);
        if (Objects.isNull(discount)) {
            // 该活动不存在或者已结束
            throw new YamiShopBindException("yami.activity.cannot.find.check");
        }
        if (!Objects.equals(SecurityUtils.getShopUser().getShopId(), discount.getShopId())) {
            throw new YamiShopBindException("yami.no.auth");
        }
        product.setLang(I18nMessage.getDbLang());
        product.setShopId(SecurityUtils.getShopUser().getShopId());
        product.setIsActive(1);
        if (Objects.equals(discount.getSuitableProdType(), 0)) {
            product.setStatus(ProdStatusEnums.NORMAL.getValue());
            IPage<Product> products = productService.pageByLang(page, product);
            return ServerResponseEntity.success(products);
        } else {
            IPage<Product> products = discountService.pageProdByDiscount(page, product, discount);
            return ServerResponseEntity.success(products);
        }
    }
}
